
var callback = null;
var receiver = null;

var SCREEN_ON = 'android.intent.action.SCREEN_ON';
var SCREEN_OFF = 'android.intent.action.SCREEN_OFF';
var USER_PRESENT = 'android.intent.action.USER_PRESENT';

/**
 * 注册监听手机屏幕事件，包括锁屏、开屏、解锁事件
 * @param {Function} c 事件回调函数
 *    回调参数event.screen, 可取值on|off|present
 */
function registerScreenEvent(c){
try{
  var os = plus.os.name;
  if('Android' == os){
    callback = c;
    receiver || (receiver=plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {  
        onReceive: function(context, intent) { //实现onReceiver回调函数
          var action = plus.android.invoke(intent, 'getAction');
          var event = {};
          if(SCREEN_ON==action){
            event.screen = 'on';
          }else if(SCREEN_OFF==action){
            event.screen = 'off';
          }else if(USER_PRESENT==action){
            event.screen = 'present';
          }else{
            return;
          }
          callback&&callback(event);
        }  
    }));
    var filter = plus.android.newObject('android.content.IntentFilter');
    plus.android.invoke(filter, 'addAction', SCREEN_ON);
    plus.android.invoke(filter, 'addAction', SCREEN_OFF);
    plus.android.invoke(filter, 'addAction', USER_PRESENT);
    var main = plus.android.runtimeMainActivity();
    main.registerReceiver(receiver, filter);
  }else{
    //unsupport, nothing to do.
  }
}catch(e){
  console.error('error @registerScreenEvent!!');
}
}

/**
 * 取消监听手机屏幕事件
 */
function unregisterScreenEvent(){
try{
  var os = plus.os.name;
  if('Android' == os){
    callback = null;
    var main = plus.android.runtimeMainActivity();
    main.unregisterReceiver(receiver);
  }else{
    //unsupport, nothing to do.
  }
}catch(e){
  console.error('error @unregisterScreenEvent!!');
}
}


module.exports = {
  register: registerScreenEvent,
  unregister: unregisterScreenEvent
}
